<template>
  <div class="login-container">
    <div class="logo" />
    <div class="form">
      <h1>黑马人力资源系统登录</h1>
      <el-card shadow="never" class="login-card">
        <!--登录表单-->
        <el-form v-if="currentLogin === 'phone'" ref="loginFormRef" :model="loginForm" :rules="rules">
          <el-form-item prop="mobile">
            <el-input v-model="loginForm.mobile" placeholder="请输入用户名" />
          </el-form-item>
          <el-form-item prop="password">
            <el-input v-model="loginForm.password" type="password" placeholder="请输入密码" />
          </el-form-item>
          <el-form-item prop="agree">
            <el-checkbox-group v-model="loginForm.agree">
              <el-checkbox label="我已阅读并同意用户协议" name="agree" />
            </el-checkbox-group>
          </el-form-item>
          <el-form-item class="login-btn">
            <el-button type="primary" style="width: 350px" @click="submit">登录</el-button>
            <!-- <el-button @click="test">测试1</el-button>
            <el-button @click="testTwo">测试2</el-button> -->
          </el-form-item>
        </el-form>
        <div v-else-if="currentLogin === 'qrcode'" class="qrcode-login">
          <div v-if="codeState === 4" class="qrcode_layer timeout">
            <span>点击刷新</span>
            <i class="el-icon-refresh-left" @click="createQrCode" />
          </div>
          <div v-if="codeState === 5" class="qrcode_layer timeout">
            <span>用户已取消</span>
            <i class="el-icon-refresh-left" @click="createQrCode" />
          </div>
          <div v-if="codeState === 2" class="qrcode_layer scan_success">
            <span>扫描成功</span>
            <i class="el-icon-check" />
          </div>
          <canvas ref="qrcodeCanvas" />
        </div>
        <div class="multi-login">
          <el-button size="mini" class="multi-button" @click="currentLogin='phone'">手机号登录</el-button>
          <el-button size="mini" class="multi-button" @click="currentLogin='qrcode'">二维码登录</el-button>
        </div>
      </el-card>
    </div>
  </div>
</template>
<script>
// import axios from 'axios'
// import request from '@/utils/request'
import { getQrCodeKeyAPI, getQrCodeStateAPI } from '@/api/user'
import QrCode from 'qrcode'
export default {
  name: 'Login',
  data() {
    return {
      // 判断当前的登录模式phone / qrcode
      currentLogin: 'phone',
      qrCodeKey: '', // 加密串变量
      // timer: null, // 定时器变量，可以不用再data中声明，因为只有响应式数据才需要在data中声明，timer只是一个标记，没有在template中使用，所以不需要响应式，只需要能够从this中读取和设置就足够了
      codeState: 1, // 轮询状态码，1-初始化，2-轮询中，3-轮询结束，4-二维码超时，5-用户取消登录
      loginForm: {
        mobile: process.env.NODE_ENV === 'development' ? '13800000002' : '',
        password: process.env.NODE_ENV === 'development' ? 'hm#qd@23!' : '',
        agree: process.env.NODE_ENV === 'development' ? ['我已阅读并同意用户协议'] : []
      },
      rules: {
        mobile: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          {
            message: '手机号格式不正确', trigger: 'blur', pattern: /^1[3-9]\d{9}$/
          }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          {
            min: 6, max: 16, message: '密码长度应该为6-16个字符', trigger: 'blur'
          }
        ],
        agree: [
          { type: 'array', required: true, message: '请同意用户协议', trigger: 'change' }
        ]
      }
    }
  },
  watch: {
    currentLogin(value) {
      if (value === 'qrcode') {
        this.createQrCode()
      } else {
        // 切换到手机号登录模式，轮询结束
        clearInterval(this.timer) // 只要不是扫码登录就停止
      }
    }
  },
  methods: {
    submit() {
      this.$refs.loginFormRef.validate(async valid => {
        if (!valid) return
        // console.log('校验成功')
        // console.log(this.loginForm)
        await this.$store.dispatch('user/login', this.loginForm)
        this.$router.push('/')
      })
    },
    // 获取加密串
    async getQrCodeKey() {
      this.qrCodeKey = await getQrCodeKeyAPI()
    },
    // 生成二维码
    async createQrCode() {
      this.codeState = 1 // 回到初始状态
      await this.getQrCodeKey()
      // 开启轮询
      this.beginLoopCheck()
      // 使用QrCode生成二维码
      // 注意点：需要使用$nextTick()，因为这个方法是在watch中监听的currentLogin的变化，此时更新还未完成，我们需要在下个事件循环中获取到dom
      this.$nextTick(() => {
        QrCode.toCanvas(this.$refs.qrcodeCanvas, this.qrCodeKey, {
          width: 300, // 二维码宽高300
          height: 300
        })
      })
    },
    // 开启轮询
    beginLoopCheck() {
      // 获取登录状态码，并进行轮询
      // 1-切换到手机号登录，轮询结束
      // 2-请求查询状态异常，轮询结束
      // 3-二维码超时，轮询结束
      // 4-页面卸载时，轮询结束
      // 5-用户扫码登录成功，轮询结束
      const checkState = async() => {
        try {
          const { codeState, token } = await getQrCodeStateAPI({ qrcode_key: this.qrCodeKey })
          this.codeState = codeState
          // 登录状态码为3（扫码登录成功）4（加密串失效）5（扫码后取消登录），轮询结束，但是3需要跳转页面
          if (this.codeState === 4 || this.codeState === 5) {
            clearInterval(this.timer)
          } else if (this.codeState === 3) {
            clearInterval(this.timer)
            // 登录设置token
            this.$store.commit('user/setToken', token)
            // 跳转到首页
            this.$router.push('/')
          }
        } catch (error) {
          console.log(error)
          // 登录异常，轮询结束
          clearInterval(this.timer)
        }
      }
      this.timer = setInterval(() => {
        checkState()
      }, 2000)
    },
    // 页面卸载时，清除定时器
    beforeDestroy() {
      clearInterval(this.timer)
    }
    // test() {
    //   // 测试VueCli的代理
    //   axios.post('/api/sys/login', this.loginForm)
    // },
    // testTwo() {
    //   // 在request中修改了baseUrl，可以省略/api
    //   request.post('/sys/login', this.loginForm)
    // }
  }
}
</script>

<style lang="scss">
.qrcode_layer {
    position: absolute;
    width: 150px;
    height: 150px;
    left: 50%;
    top: 50%;
    transform: translate(-75px, -75px);
    opacity: 0.9;
    background: #e1dede;
    display: flex;
    justify-content: center;
    align-items: center;
    i {
      font-size: 40px;
      padding: 10px;
    }
  }
  .scan_success {
    i {
      color: #67C23A;
    }
  }
  .timeout {
    i {
      color: #F56C6C;
    }
  }
.qrcode-login {
    width: 350px;
    padding: 10px;
    display: flex;
    justify-content: center;
    align-items: center;
    position: relative;
  }
.multi-login {
    margin: 10px 0;
    display: flex;
    width: 350px;
    .multi-button {
      flex: 1;
    }
  }
.login-container {
  display: flex;
  align-items: stretch;
  height: 100vh;

  .logo {
    flex: 3;
    background: rgba(38, 72, 176) url(../../assets/common/login_back.png) no-repeat center / cover;
    border-top-right-radius: 60px;
    display: flex;
    flex-direction: column;
    align-items: flex-end;
    justify-content: center;
    padding: 0 100px;

    .icon {
      background: url(../../assets/common/logo.png) no-repeat 70px center / contain;
      width: 300px;
      height: 50px;
      margin-bottom: 50px;
    }

    p {
      color: #fff;
      font-size: 18px;
      margin-top: 20px;
      width: 300px;
      text-align: center;
    }
  }

  .form {
    flex: 2;
    display: flex;
    flex-direction: column;
    justify-content: center;
    padding-left: 176px;

    .el-card {
      border: none;
      padding: 0;
    }

    h1 {
      padding-left: 20px;
      font-size: 24px;
    }

    .el-input {
      width: 350px;
      height: 44px;

      .el-input__inner {
        background: #f4f5fb;
      }
    }

    .el-checkbox {
      color: #606266;
    }
  }
}
</style>
